#AUTHOR:     Ravi Prakash
#            Department of Computer Science
#            University of Southern California, Los Angeles
import pickle
import olpcgames.mesh as mesh
import pygame
from olpcgames import *

def SendAll(gamestate): #needs to be called whenever gamestate is changed. Communicates the change to all the other players
    mesh.broadcast(pickle.dumps(gamestate))
    
def HandleEvent(event, gamestate):
    if event.type==mesh.CONNECT: #Game connected to the mesh
        print "Connected to mesh"
        pass
        
    if event.type==mesh.PARTICIPANT_ADD:
        print "A new participant has started sharing the XO Muncher activity"
        def AddPlayer(buddy):
            if buddy!=mesh.my_handle():
                gamestate.PlayerList.AddPlayer(buddy.props.nick)                
        mesh.lookup_buddy(event.handle, callback=AddPlayer)
        
    if event.type==mesh.MESSAGE_MULTI or event.type==mesh.MESSAGE_UNI:
        print "A new message was received"
        msg=event.content
        gs=pickle.loads(msg) #Now gs is a GameState class with which we wanna replace current GameState class
        gamestate.MonsterList=gs.MonsterList #Copy monsterList into this player's state
        gamestate.GameBoard=gs.GameBoard #Copy GameBoard into this player's state
        #need to copy PlayerList 
        #gamestate.PlayerList=gs.PlayerList #This won't do 
        #Just accept the score of the player that sent the message
        def ChangePlayerScore(buddy):
            i=gamestate.PlayerList.FindIndex(buddy.props.nick)
            j=gs.PlayerList.FindIndex(gs.local_player) 
            gamestate.PlayerList[i:i+6]=gs.PlayerList[j:j+6]
        mesh.lookup_buddy(event.handle, callBack=ChangePlayerScore)
